/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.numbers.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;

import static axil.framework.Functions.unreachable;


/**
 * An Axil implementation of a number with arbitrary precision.
 */
public class Decimal extends Num {
	public static final AxilType type = Decimal_Type.object;
	public static final Decimal zero = new Decimal(BigDecimal.ZERO);


	/**
	 * Do NOT rearrange these!  These are ordered by the ordinal value of the
	 * rounding mode so that we have fast lookup into a static cache of contexts.
	 */
	private static final MathContext[] contexts = {
		new MathContext(1, RoundingMode.UP),
		new MathContext(1, RoundingMode.DOWN),
		new MathContext(1, RoundingMode.CEILING),
		new MathContext(1, RoundingMode.FLOOR),
		new MathContext(1, RoundingMode.HALF_UP),
		new MathContext(1, RoundingMode.HALF_DOWN),
		new MathContext(1, RoundingMode.HALF_EVEN)
	};

	private final BigDecimal value;


	public Decimal(BigDecimal value) {
		this.value = value;
	}


	public static Decimal from(String value) {
		return new Decimal(new BigDecimal(value));
	}


	public static Decimal from(BigDecimal value) {
		if (value == BigDecimal.ZERO) {
			return zero;
		}
		return new Decimal(value);
	}


	public static Decimal from(Number number) {
		if (number instanceof BigDecimal) {
			return from((BigDecimal)number);
		}
		if ((number instanceof Double) || (number instanceof Float)) {
			return from(number.doubleValue());
		}
		if (number instanceof BigInteger) {
			return from(new BigDecimal((BigInteger)number));
		}
		return from(new BigDecimal(number.intValue()));
	}


	public static Decimal from(double value) {
		if (value == 0.0D) {
			return zero;
		}
		return new Decimal(new BigDecimal(value));
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Tell the magnitude of this numeric value. This is used in all arithmetic
	 * computations to ensure like objects are used.
	 */
	public int kind() {
		return DECIMAL;
	}


	/**
	 * Return the value of this object as an object of the indicated size. It
	 * can be safely assumed that the caller intended whatever side effects
	 * occur as part of the conversion are intentional.
	 */
	public Num as(int kind) {
		switch(kind) {
		case INT:
			return Int.from(value.intValue());
		case BIGINT:
			return BigInt.from(value.longValue());
		case FP:
			return FloatingPoint.from(value.doubleValue());
		case DECIMAL:
			return this;
		case PERCENT:
			return new Percent(this);
		case FRACTION:
			return Fraction.from(this);

		default:
			throw unreachable();
		}
	}


	/**
	 * Return the canonical representation of a zero value in this numeric
	 * type.
	 */
	public Num zero() {
		return zero;
	}


	/**
	 * Tell if this number has any significant fractional digits. For example,
	 * the number 3.1 would return true, but 3.0 would not.
	 */
	public boolean fractional() {
		if (value.scale() <= 0) {
			return false;
		}
		String s = value.toString();
		int dp = s.indexOf('.');
		final int size = s.length();
		for (int i = dp + 1; i < size; i++) {
			final char ch = s.charAt(i);
			if ((ch >= '1') && (ch <= '9')) {
				return true;
			}
		}
		return false;
	}


	/**
	 * Get this value as an integer value, discarding any fractional component.
	 * For example, 12.65 returns the integer value 12. No rounding is performed,
	 * only truncation. If the value is greater than what can fit in a 64-bit
	 * integer, then an exception is thrown.
	 */
	public long whole() {
		String s = value.toString();
		final int i = s.indexOf('.');
		if (i > 0) {
			s = s.substring(0, i);
		}
		return Long.parseLong(s);
	}


	/**
	 * Get the fractional portion of this numeric value as a floating point
	 * value. For example, 12.325 returns a value of 0.325. If there is no
	 * fractional portion, then 0.0 is returned.
	 */
	public double tenths() {
		String s = value.toString();
		final int i = s.indexOf('.');
		if (i > 0) {
			if ((i == 1) && (s.charAt(0) == '0')) {
				return 0.0D;
			}
			s = s.substring(i + 1);
			if (s.length() > 14) {
				s = s.substring(0, 13);
			}
			return Double.valueOf("0." + s);
		}
		return 0.0D;
	}


	/**
	 * Return a true value if this number is greater than zero. A value of zero
	 * returns a false value.
	 */
	public boolean positive() {
		return value.signum() > 0;
	}


	/**
	 * Return a floating point representation of this object. It is understood
	 * the some loos of information may result. Invoking this method is
	 * accepting that side effect.
	 */
	public double fp() {
		return value.doubleValue();
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return value.hashCode();
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		if (object instanceof Num) {
			Num n = (Num)object;
			switch(n.kind()) {
			case INT:
				if (fractional()) {
					return false;
				}
				return equalTo(n.as(DECIMAL));

			case BIGINT:
				if (fractional()) {
					return false;
				}
				return equalTo(n.as(DECIMAL));

			case FRACTION:
				return equalTo(n.as(DECIMAL));
			case FP:
				return fp() == n.fp();
			case PERCENT:
				return fp() == n.fp();
			case DECIMAL:
				return value.compareTo(((Decimal)n).value) == 0;
			case UNITIZED:
				return equalTo(mag(n));

			default:
				throw unreachable();
			}
		}
		return false;
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
		if (object instanceof Decimal) {
			return value.compareTo(((Decimal)object).value);
		}
		Num n = num(object);
		int kind = upcast(this, n);
		return as(kind).comparedTo(n.as(kind));
	}


	/**
	 * Compares this object with the specified object for order.  Returns a
	 * negative integer, zero, or a positive integer as this object is less
	 * than, equal to, or greater than the specified object. This method can
	 * safely assume that the given value is not null and is of the exact same
	 * type as this value.
	 */
	public int compare(Num n) {
		Decimal v = (Decimal)n;
		return value.compareTo(v.value);
	}


	/**
	 * Given a BigDecimal object, get rid of any non-significant digits to the
	 * right of the decimal point. That is, 125.5000 becomes 125.5, and 47.00
	 * becomes 47.
	 */
	static BigDecimal tighten(BigDecimal num) {
		String s = num.toString();
		int i = s.indexOf('.');
		if (i < 0) {
			return num;
		}
		int last = i + 1;
		final int end = s.length();
		for (int k = last; k < end; k++) {
			if (s.charAt(k) != '0') {
				last = k;
			}
		}
		if ((last == (i + 1)) && (s.charAt(last) == '0')) {
			s = s.substring(0, i);
		} else {
			s = s.substring(0, last + 1);
		}
		return new BigDecimal(s);
	}


	/**
	 * Add the given number of this number. This method can safely assume that
	 * the given value is not null and is of the exact same type as this value.
	 */
	public AxilObject add(AxilObject n) {
		if (n instanceof Decimal) {
            Decimal v = (Decimal) n;
            return new Decimal(value.add(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).add(v.as(kind));
        }
	}


	/**
	 * Subtract the given number from this number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public AxilObject subtract(AxilObject n) {
        if (n instanceof Decimal) {
            Decimal v = (Decimal) n;
            return new Decimal(value.subtract(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).subtract(v.as(kind));
        }
	}


	/**
	 * Multiply the given number by this number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public Num multiply(Num n) {
        if (n instanceof Decimal) {
            Decimal v = (Decimal) n;
            return new Decimal(value.multiply(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).multiply(v.as(kind));
        }
	}


	/**
	 * Divide this number by the given number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public Num divide(Num n) {
        if (n instanceof Decimal) {
            Decimal v = (Decimal) n;
            return new Decimal(tighten(value.divide(v.value, 30, RoundingMode.HALF_EVEN)));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).divide(v.as(kind));
        }
	}


	/**
	 * Round this value according to the rules of the given rounding mode and
	 * to the given number of significant fractional digits. A value of zero
	 * rounds this to a whole number.
	 */
	public Num round(RoundingMode mode, int digits) {
        // In Java, scale is the number of digits to the right of the decimal. See Issue#58 for details.
        return from(value.setScale(digits, contexts[mode.ordinal()].getRoundingMode()));
	}


	/**
	 * Return the host application (or built-in Java) object that most closely
	 * matches this value object. Return returned value is never null unless
	 * this value object represents the special 'nil' object.
	 */
	public Object intrinsic() {
		return value;
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		// TODO: Need better formatting here
		return value.toString();
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		// TODO: Need better formatting here
		return value.toString();
	}
}
